import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'dart:math' as math;

// مال مودېلى (ۋاقىتلىق)
class Product {
  final String id;
  final String name;
  final double price;
  final int stock;
  final String unit;
  final String category;

  Product({
    required this.id,
    required this.name,
    required this.price,
    required this.stock,
    required this.unit,
    required this.category,
  });
}

// خېرىدار مودېلى (ۋاقىتلىق)
class Customer {
  final String id;
  final String name;
  final String phone;
  final String address;

  Customer({
    required this.id,
    required this.name,
    required this.phone,
    required this.address,
  });
}

// ۋاقىتلىق مال سانلىق مەلۇماتلىرى
final List<Product> _demoProducts = List.generate(
  20,
  (index) => Product(
    id: 'P-${(100 + index).toString().padLeft(3, '0')}',
    name: 'مال ${index + 1}',
    price: (10 + math.Random().nextInt(990)).toDouble(),
    stock: math.Random().nextInt(100) + 10,
    unit: _getRandomUnit(),
    category: _getRandomCategory(),
  ),
);

// ۋاقىتلىق خېرىدار سانلىق مەلۇماتلىرى
final List<Customer> _demoCustomers = List.generate(
  10,
  (index) => Customer(
    id: 'C-${(100 + index).toString().padLeft(3, '0')}',
    name: 'خېرىدار ${index + 1}',
    phone: '1${(3100000000 + math.Random().nextInt(899999999)).toString()}',
    address: 'ئادرېس ${index + 1}',
  ),
);

// تەسادىپىي تۈرنى قايتۇرىدۇ
String _getRandomCategory() {
  final categories = [
    'كىيىم-كېچەك',
    'ئېلېكترونلۇق',
    'ئاشلىق',
    'ئۆي جابدۇقلىرى',
    'كىتاب',
    'باشقا'
  ];
  return categories[math.Random().nextInt(categories.length)];
}

// تەسادىپىي بىرلىكنى قايتۇرىدۇ
String _getRandomUnit() {
  final units = ['دانە', 'كىلوگرام', 'پاكېت', 'قۇتا', 'مېتىر'];
  return units[math.Random().nextInt(units.length)];
}

// سېتىلىدىغان مال تۈرى
class CartItem {
  final Product product;
  int quantity;
  final double discount;

  CartItem({
    required this.product,
    required this.quantity,
    this.discount = 0.0,
  });

  double get total => product.price * quantity * (1 - discount / 100);
}

class AddSaleScreen extends StatefulWidget {
  const AddSaleScreen({Key? key}) : super(key: key);

  @override
  State<AddSaleScreen> createState() => _AddSaleScreenState();
}

class _AddSaleScreenState extends State<AddSaleScreen> {
  final _formKey = GlobalKey<FormState>();
  Customer? _selectedCustomer;
  String _paymentMethod = 'نەق پۇل';
  final List<CartItem> _cartItems = [];
  DateTime _saleDate = DateTime.now();
  String _notes = '';
  double _discountPercentage = 0;

  // ساتىدىغان ماللارنى ساقلايدىغان ۋاقىتلىق ساقلىغۇچ
  final TextEditingController _searchController = TextEditingController();
  List<Product> _searchResults = [];
  bool _isSearching = false;

  @override
  void initState() {
    super.initState();
    _searchResults = List.from(_demoProducts);
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  // مال ئىزدەش
  void _searchProducts(String query) {
    setState(() {
      if (query.isEmpty) {
        _searchResults = List.from(_demoProducts);
        _isSearching = false;
      } else {
        _isSearching = true;
        _searchResults = _demoProducts
            .where((product) =>
                product.name.toLowerCase().contains(query.toLowerCase()) ||
                product.id.toLowerCase().contains(query.toLowerCase()) ||
                product.category.toLowerCase().contains(query.toLowerCase()))
            .toList();
      }
    });
  }

  // سېۋەتكە مال قوشۇش
  void _addToCart(Product product) {
    setState(() {
      // ئاللىقاچان سېۋەتتە بار بولسا سانىنى كۆپەيتىش
      final existingItemIndex =
          _cartItems.indexWhere((item) => item.product.id == product.id);
      if (existingItemIndex != -1) {
        _cartItems[existingItemIndex].quantity++;
      } else {
        _cartItems.add(CartItem(product: product, quantity: 1));
      }
    });

    // قوشۇلغاندىن كېيىن ئۇچۇر كۆرسىتىش
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('${product.name} سېۋەتكە قوشۇلدى'),
        duration: const Duration(seconds: 1),
        backgroundColor: Colors.green,
      ),
    );
  }

  // سېۋەتتىن مال ئۆچۈرۈش
  void _removeFromCart(int index) {
    setState(() {
      _cartItems.removeAt(index);
    });
  }

  // سودىنى تاماملاش
  void _completeSale() {
    if (_formKey.currentState!.validate()) {
      if (_cartItems.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('سېۋەت قۇرۇق، مال قوشۇڭ'),
            backgroundColor: Colors.red,
          ),
        );
        return;
      }

      if (_selectedCustomer == null) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('خېرىدار تاللانمىدى'),
            backgroundColor: Colors.red,
          ),
        );
        return;
      }

      // بۇ يەردە يېڭى سودا ساقلىنىدۇ
      // ھەقىقىي پروجېكتتە، بۇ مەلۇماتلار مەلۇمات ئامبىرىغا ساقلىنىدۇ
      // ۋاقىتلىق مۇۋەپپەقىيەت ئۇچۇرى كۆرسىتىپ، ئالدىنقى بەتكە قايتىمىز

      // سودا تاماملاندى
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('سودا مۇۋەپپەقىيەتلىك تاماملاندى'),
          backgroundColor: Colors.green,
        ),
      );

      // ئالدىنقى بەتكە قايتىش
      Navigator.pop(context, true);
    }
  }

  // جەمئىي سوممىنى ھېسابلايدۇ
  double _calculateTotal() {
    return _cartItems.fold<double>(
          0,
          (sum, item) => sum + item.total,
        ) *
        (1 - _discountPercentage / 100);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('يېڭى سودا قوشۇش'),
        actions: [
          IconButton(
            icon: const Icon(Icons.save),
            onPressed: _completeSale,
          ),
        ],
      ),
      body: Form(
        key: _formKey,
        child: Column(
          children: [
            Expanded(
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // مال تاللاش قىسمى
                  Expanded(
                    flex: 3,
                    child: Card(
                      margin: const EdgeInsets.all(8),
                      child: Padding(
                        padding: const EdgeInsets.all(16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // ئىزدەش
                            TextField(
                              controller: _searchController,
                              decoration: InputDecoration(
                                hintText: 'مال ئىزدەش...',
                                prefixIcon: const Icon(Icons.search),
                                suffixIcon: IconButton(
                                  icon: const Icon(Icons.clear),
                                  onPressed: () {
                                    _searchController.clear();
                                    _searchProducts('');
                                  },
                                ),
                                border: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(8),
                                ),
                              ),
                              onChanged: _searchProducts,
                            ),
                            const SizedBox(height: 16),

                            // ئىزدەش نەتىجىسى
                            Expanded(
                              child: _isSearching && _searchResults.isEmpty
                                  ? const Center(
                                      child: Text('مال تېپىلمىدى'),
                                    )
                                  : ListView.builder(
                                      itemCount: _searchResults.length,
                                      itemBuilder: (context, index) {
                                        final product = _searchResults[index];
                                        return ListTile(
                                          title: Text(product.name),
                                          subtitle: Text(
                                            '${product.category} | باھا: ¥${product.price.toStringAsFixed(2)} | ساقلىغۇچ: ${product.stock} ${product.unit}',
                                          ),
                                          trailing: ElevatedButton(
                                            onPressed: () =>
                                                _addToCart(product),
                                            child: const Text('قوشۇش'),
                                          ),
                                        );
                                      },
                                    ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),

                  // سودا مەلۇماتلىرى ۋە سېۋەت قىسمى
                  Expanded(
                    flex: 2,
                    child: Column(
                      children: [
                        // سودا مەلۇماتلىرى
                        Card(
                          margin: const EdgeInsets.all(8),
                          child: Padding(
                            padding: const EdgeInsets.all(16),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const Text(
                                  'سودا مەلۇماتلىرى',
                                  style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                const SizedBox(height: 16),

                                // خېرىدار تاللاش
                                DropdownButtonFormField<Customer>(
                                  decoration: const InputDecoration(
                                    labelText: 'خېرىدار',
                                    border: OutlineInputBorder(),
                                  ),
                                  hint: const Text('خېرىدار تاللاڭ'),
                                  value: _selectedCustomer,
                                  items: _demoCustomers
                                      .map((customer) =>
                                          DropdownMenuItem<Customer>(
                                            value: customer,
                                            child: Text(customer.name),
                                          ))
                                      .toList(),
                                  onChanged: (value) {
                                    setState(() {
                                      _selectedCustomer = value;
                                    });
                                  },
                                ),
                                const SizedBox(height: 16),

                                // سودا چېسلاسى
                                InkWell(
                                  onTap: () async {
                                    final date = await showDatePicker(
                                      context: context,
                                      initialDate: _saleDate,
                                      firstDate: DateTime(2020),
                                      lastDate: DateTime.now()
                                          .add(const Duration(days: 1)),
                                    );
                                    if (date != null) {
                                      setState(() {
                                        _saleDate = date;
                                      });
                                    }
                                  },
                                  child: InputDecorator(
                                    decoration: const InputDecoration(
                                      labelText: 'سودا چېسلاسى',
                                      border: OutlineInputBorder(),
                                    ),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(DateFormat('yyyy-MM-dd')
                                            .format(_saleDate)),
                                        const Icon(Icons.calendar_today),
                                      ],
                                    ),
                                  ),
                                ),
                                const SizedBox(height: 16),

                                // تۆلەش ئۇسۇلى
                                DropdownButtonFormField<String>(
                                  decoration: const InputDecoration(
                                    labelText: 'تۆلەش ئۇسۇلى',
                                    border: OutlineInputBorder(),
                                  ),
                                  value: _paymentMethod,
                                  items: [
                                    'نەق پۇل',
                                    'ئېلېكترونلۇق تۆلەم',
                                    'ئالىپاي',
                                    'ۋېچات تۆلەم',
                                    'باشقا'
                                  ]
                                      .map((method) => DropdownMenuItem<String>(
                                            value: method,
                                            child: Text(method),
                                          ))
                                      .toList(),
                                  onChanged: (value) {
                                    setState(() {
                                      _paymentMethod = value!;
                                    });
                                  },
                                ),
                                const SizedBox(height: 16),

                                // ئومۇمىي چېگىرما
                                TextFormField(
                                  decoration: const InputDecoration(
                                    labelText: 'ئومۇمىي چېگىرما (%)',
                                    border: OutlineInputBorder(),
                                  ),
                                  keyboardType: TextInputType.number,
                                  initialValue: _discountPercentage.toString(),
                                  onChanged: (value) {
                                    setState(() {
                                      _discountPercentage =
                                          double.tryParse(value) ?? 0;
                                    });
                                  },
                                ),
                                const SizedBox(height: 16),

                                // ئىزاھات
                                TextFormField(
                                  decoration: const InputDecoration(
                                    labelText: 'ئىزاھات',
                                    border: OutlineInputBorder(),
                                  ),
                                  maxLines: 2,
                                  onChanged: (value) {
                                    _notes = value;
                                  },
                                ),
                              ],
                            ),
                          ),
                        ),

                        // سېۋەت قىسمى
                        Expanded(
                          child: Card(
                            margin: const EdgeInsets.all(8),
                            child: Padding(
                              padding: const EdgeInsets.all(16),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      const Text(
                                        'سېۋەت',
                                        style: TextStyle(
                                          fontSize: 16,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                      _cartItems.isNotEmpty
                                          ? TextButton.icon(
                                              icon: const Icon(Icons.delete,
                                                  size: 16),
                                              label:
                                                  const Text('ھەممىنى تازىلاش'),
                                              onPressed: () {
                                                setState(() {
                                                  _cartItems.clear();
                                                });
                                              },
                                            )
                                          : const SizedBox(),
                                    ],
                                  ),
                                  const SizedBox(height: 8),

                                  // سېۋەت مەزمۇنى
                                  Expanded(
                                    child: _cartItems.isEmpty
                                        ? const Center(
                                            child: Text('سېۋەت قۇرۇق'),
                                          )
                                        : ListView.builder(
                                            itemCount: _cartItems.length,
                                            itemBuilder: (context, index) {
                                              final item = _cartItems[index];
                                              return ListTile(
                                                contentPadding: EdgeInsets.zero,
                                                title: Text(item.product.name),
                                                subtitle: Row(
                                                  children: [
                                                    Text(
                                                        'باھا: ¥${item.product.price.toStringAsFixed(2)}'),
                                                    const SizedBox(width: 10),
                                                    Text(
                                                        'جەمئىي: ¥${item.total.toStringAsFixed(2)}'),
                                                  ],
                                                ),
                                                trailing: Row(
                                                  mainAxisSize:
                                                      MainAxisSize.min,
                                                  children: [
                                                    IconButton(
                                                      icon: const Icon(
                                                          Icons.remove_circle),
                                                      onPressed: () {
                                                        setState(() {
                                                          if (item.quantity >
                                                              1) {
                                                            item.quantity--;
                                                          } else {
                                                            _cartItems.removeAt(
                                                                index);
                                                          }
                                                        });
                                                      },
                                                    ),
                                                    SizedBox(
                                                      width: 40,
                                                      child: Text(
                                                        '${item.quantity}',
                                                        textAlign:
                                                            TextAlign.center,
                                                        style: const TextStyle(
                                                          fontWeight:
                                                              FontWeight.bold,
                                                        ),
                                                      ),
                                                    ),
                                                    IconButton(
                                                      icon: const Icon(
                                                          Icons.add_circle),
                                                      onPressed: () {
                                                        setState(() {
                                                          item.quantity++;
                                                        });
                                                      },
                                                    ),
                                                  ],
                                                ),
                                              );
                                            },
                                          ),
                                  ),

                                  // جەمئىي سومما
                                  const Divider(),
                                  Padding(
                                    padding:
                                        const EdgeInsets.symmetric(vertical: 8),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        const Text(
                                          'جەمئىي سومما:',
                                          style: TextStyle(
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                        Text(
                                          '¥${_calculateTotal().toStringAsFixed(2)}',
                                          style: const TextStyle(
                                            fontWeight: FontWeight.bold,
                                            fontSize: 18,
                                            color: Colors.blue,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),

            // سودىنى تاماملاش كۇنۇپكىسى
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(16),
              child: ElevatedButton.icon(
                onPressed: _completeSale,
                icon: const Icon(Icons.check_circle),
                label: const Text('سودىنى تاماملاش'),
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
